package com.playball.lottery.util;

import java.io.IOException;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.media.SoundPool;
import android.os.Vibrator;

public class SoundManage {

    // 获取声音文件,MediaPlayer播放声音,常
    public static void OnPlaySound(Context context, String filename) {
	try {
	    AssetFileDescriptor   fileDescriptor = context.getResources().getAssets().openFd(filename);
	    MediaPlayer mp = new MediaPlayer();
	    mp.setDataSource(fileDescriptor.getFileDescriptor(), fileDescriptor.getStartOffset(), fileDescriptor.getLength());
	    mp.prepare();
	    mp.start();
	    // 内部的播放引擎会调用客户端程序员提供的OnSeekComplete.onSeekComplete()回调方法
	    mp.setOnSeekCompleteListener(new OnSeekCompleteListener() {
		@Override
		public void onSeekComplete(MediaPlayer mp) {
		    // TODO Auto-generated method stub
		    // End状态，只要MediaPlayer对象不再被使用
		    mp.release();
		}
	    });
	} catch (IOException e) {
	    // TODO Auto-generated catch block
//	    e.printStackTrace();
	}
    }

    // 获取声音文件,SoundPool播放声音,短
    public static void OnPlaySoundPool(Context context, String filename) {
	try {
	    AssetFileDescriptor fileDescriptor = context.getResources().getAssets().openFd(filename);
	    /*
	     * maxStream —— 同时播放的流的最大数量 streamType ——
	     * 流的类型，一般为STREAM_MUSIC(具体在AudioManager类中列出) srcQuality ——
	     * 采样率转化质量，当前无效果，使用0作为默认值
	     */
	    SoundPool soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
	    int soundId = soundPool.load(fileDescriptor, 1); // 从Asset对象载入
	    // 安卓1.6不支持setOnLoadCompleteListener
	    // soundPool.setOnLoadCompleteListener(new
	    // SoundPool.OnLoadCompleteListener() {
	    // @Override
	    // public void onLoadComplete(SoundPool soundPool, int sampleId, int
	    // status) {
	    // // TODO Auto-generated method stub
	    // soundPool.play(soundId, 1, 1, 0, 0, 1);
	    // }
	    // });
	    soundPool.play(soundId, 1, 1, 0, 0, 1);

	} catch (IOException e) {
	    // TODO Auto-generated catch block
//	    e.printStackTrace();
	}
    }

    // 产生震动
    public static void OnVibator(Context context, long timelong) {
	Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
	if (vibrator == null) {
	    Vibrator localVibrator = (Vibrator) context.getApplicationContext().getSystemService("vibrator");
	    vibrator = localVibrator;
	}
	vibrator.vibrate(timelong);
    }

}
